package com.niit.onlinemusic.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.niit.onlinemusic.common.R;
import com.niit.onlinemusic.constant.Constants;
import com.niit.onlinemusic.mapper.ConsumerMapper;
import com.niit.onlinemusic.model.domain.Consumer;
import com.niit.onlinemusic.model.request.ConsumerRequest;
import com.niit.onlinemusic.service.ConsumerService;
import org.apache.logging.log4j.util.Strings;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;

/**
 * (Consumer)表服务实现类
 *
 * @author makejava
 * @since 2025-09-17 09:03:36
 */
@Service
public class ConsumerServiceImpl extends ServiceImpl<ConsumerMapper, Consumer> implements ConsumerService {

    private final ConsumerMapper consumerMapper;

    public ConsumerServiceImpl(ConsumerMapper consumerMapper) {
        this.consumerMapper = consumerMapper;
    }

    @Override
    public R allUser(IPage<Consumer> page) {
        return R.success("查询成功", consumerMapper.selectPage(page, null));
    }

    @Override
    public R loginStatus(ConsumerRequest consumerRequest, HttpSession session) {
        String username = consumerRequest.getUsername();
        String password = consumerRequest.getPassword();
        if (Strings.isBlank(username) || Strings.isBlank(password)) {
            return R.error("用户名或密码不能为空");
        } else {

            if (this.verityPasswd(username, password)) {
                session.setAttribute("username", username);
                Consumer consumer = new Consumer();
                consumer.setUsername(username);
                return R.success("登录成功", consumerMapper.selectList(new QueryWrapper<>(consumer)));
            } else {
                return R.error("用户名或密码错误");
            }
        }
    }

    @Override
    public boolean verityPasswd(String username, String password) {
        QueryWrapper<Consumer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        String secretPassword = DigestUtils.md5DigestAsHex((Constants.SALT + password).getBytes(StandardCharsets.UTF_8));
        queryWrapper.eq("password", secretPassword);
        return consumerMapper.selectCount(queryWrapper) > 0;
    }

    @Override
    public R updateAvatar(MultipartFile multipartFile, Long id) {
        // 1.将multipartFile保存到服务器中
        // 获取图片的名字
        String fileName = System.currentTimeMillis() + "-" + multipartFile.getOriginalFilename();
        // 设置图片保存到服务器的路径: 当前项目路径+img+avatorImages
        String filePath = System.getProperty("user.dir") + System.getProperty("file.separator") + "img" + System.getProperty("file.separator") + "avatorImages";
        System.out.println("filePath=" + filePath);
        // 创建该文件夹
        File file = new File(filePath);
        if (!file.exists() && !file.mkdirs()) {
            return R.fatal("创建文件失败");
        }
        // 将二进制流转成文件，保存到相应的文件夹下
        File dest = new File(filePath + System.getProperty("file.separator") + fileName);
        // 设置保存到数据库中的图片路径
        String imgPath = "/img/avatorImages/" + fileName;
        try {
            // 将二进制流转成文件
            multipartFile.transferTo(dest);
        } catch (IOException e) {
            return R.fatal("上传失败" + e.getMessage());
        }
        // 2.得到图片的新的路径，将其更新到数据库表中
        Consumer consumer = new Consumer();
        consumer.setId(id);
        consumer.setAvator(imgPath);
        consumer.setUpdateTime(LocalDateTime.now());
        int rows = consumerMapper.updateById(consumer);
        if (rows > 0) {
            return R.success("更新成功", imgPath);
        } else {
            return R.error("更新失败");
        }
    }

}
